<!-- components/ClustrMap.vue -->
<template>
  <a href="https://clustrmaps.com/site/1c5za" title="ClustrMaps"
    ><img
      src="//www.clustrmaps.com/map_v2.png?d=i7nibn76VOjErjYZT32IAkkycuD3sbLVWFv4dmByI4s&cl=ffffff&w=a"
  /></a>
  <!-- <a href=" " title="ClustrMaps">
    <img  src="//www.clustrmaps.com/map_v2.png?d=i7nibn76VOjErjYZT32IAkkycuD3sbLVWFv4dmByI4s&cl=ffffff" />
  </a> -->
  <client-only>
    <div
      ref="mapContainer"
      class="w-full"
      data-cmap="loading"
      id="clustrmaps-widget"
    />
  </client-only>
</template>

<script setup lang="ts">
import { onMounted, ref, onBeforeUnmount } from "vue";

const mapContainer = ref<HTMLElement | null>(null);
const CLUSTR_ID = "i7nibn76VOjErjYZT32IAkkycuD3sbLVWFv4dmByI4s"; // 从环境变量读取更佳
let mapScript: HTMLScriptElement | null = null;

onMounted(() => {
  if (!mapContainer.value) return;

  // 确保之前的脚本被移除（如果存在）
  const existingScript = document.getElementById("clustrmaps");
  if (existingScript) {
    existingScript.remove();
  }

  // 创建一个全局变量，ClustrMaps可能需要这个来初始化
  window._clustrmaps = window._clustrmaps || {};

  // 动态创建脚本标签
  mapScript = document.createElement("script");
  mapScript.id = "clustrmaps";
  mapScript.src = `//clustrmaps.com/map_v2.js?d=i7nibn76VOjErjYZT32IAkkycuD3sbLVWFv4dmByI4s&cl=ffffff&w=a`;

  // 添加必要的属性
  mapScript.type = "text/javascript";
  mapScript.async = true;

  // 状态追踪
  mapScript.onload = () => {
    if (mapContainer.value) {
      mapContainer.value.setAttribute("data-cmap", "loaded");
      console.log("ClustrMaps script loaded successfully");
    }
  };

  mapScript.onerror = (e) => {
    if (mapContainer.value) {
      mapContainer.value.setAttribute("data-cmap", "error");
      console.error("Failed to load ClustrMaps script:", e);
    }
  };

  // 将脚本添加到文档头部而不是容器内
  document.head.appendChild(mapScript);
});

onBeforeUnmount(() => {
  // 清理脚本，避免内存泄漏
  if (mapScript && mapScript.parentNode) {
    mapScript.parentNode.removeChild(mapScript);
  }
});
</script>

<style>
[data-cmap="loading"] {
  @apply animate-pulse bg-gray-100;
}

[data-cmap="error"] {
  @apply border-2 border-red-500;
}
</style>
